#include <mc/crosshair.h>
#include <mc/mcwidget.h>
#include <opengl/texture.h>
#include <iostream>

namespace mc
{
opengl::Shader Crosshair::shader;

#define CROSS_SIZE 0.025f
#define CROSS_SCALE 0.8f

float Crosshair::vertices[] =  {
    -CROSS_SCALE * CROSS_SIZE,  CROSS_SIZE,  0.0f,  1.0f,
    -CROSS_SCALE * CROSS_SIZE, -CROSS_SIZE,  0.0f,  0.0f,
     CROSS_SCALE * CROSS_SIZE, -CROSS_SIZE,  1.0f,  0.0f,
     CROSS_SCALE * CROSS_SIZE, -CROSS_SIZE,  1.0f,  0.0f,
     CROSS_SCALE * CROSS_SIZE,  CROSS_SIZE,  1.0f,  1.0f,
    -CROSS_SCALE * CROSS_SIZE,  CROSS_SIZE,  0.0f,  1.0f,
};

Crosshair::Crosshair(const std::string& texturePath) : 
    _texture(nullptr), _vao{}, _vbo{}
{
    this->_vao.bind();
    this->_vbo.bind();
    this->_vbo.setBufferData(sizeof(Crosshair::vertices), Crosshair::vertices, GL_STATIC_DRAW);
    this->_vao.setVertexAttribPointer(0, 2, GL_FLOAT, 4 * sizeof(float), (void*)0);
    this->_vao.setVertexAttribPointer(1, 2, GL_FLOAT, 4 * sizeof(float), (void*)(2 * sizeof(float)));
    this->_texture = opengl::Texture::load2DTexture(texturePath);
}

Crosshair::~Crosshair() noexcept
{
#ifdef DEBUG
    std::cout << "free crosshair(vao, vbo)\n";
#endif
    this->_vao.free();
    this->_vbo.free();
}

void Crosshair::draw()
{
    this->_vao.bind();
    Crosshair::shader.setInt("tex", this->_texture->index());
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);
}

void Crosshair::createShader()
{
    // 着色器程序
    Crosshair::shader = opengl::Shader("./resources/shaders/crosshair.vert", "./resources/shaders/crosshair.frag");
}

void Crosshair::prepareRender()
{
    Crosshair::shader.bind();
}

}